<!DOCTYPE html>
<html lang="zh-Hans">
<head>

    <!--[if lt IE 9]>
        <style>body {display: none; background: none !important} </style>
        <meta http-equiv="Refresh" Content="0; url=//outdatedbrowser.com/" />
    <![endif]-->

<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge, chrome=1" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no">
<meta name="format-detection" content="telephone=no" />
<meta name="author" content="HatBoy" />



<meta name="description" content="组织Cython代码">
<meta name="keywords" content="Python,Cython">
<meta property="og:type" content="article">
<meta property="og:title" content="第六章 组织Cython代码">
<meta property="og:url" content="http://hatboy.gitee.io/2017/08/16/第六章-组织Cython代码/index.html">
<meta property="og:site_name" content="HatBoy的个人主页">
<meta property="og:description" content="组织Cython代码">
<meta property="og:locale" content="zh-Hans">
<meta property="og:updated_time" content="2017-12-21T10:15:28.330Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="第六章 组织Cython代码">
<meta name="twitter:description" content="组织Cython代码">

<link rel="apple-touch-icon" href= "/apple-touch-icon.png">


    <link rel="alternate" href="/atom.xml" title="HatBoy的个人主页" type="application/atom+xml">



    <link rel="shortcut icon" href="/img/favicon.ico">



    <link href="//cdn.bootcss.com/animate.css/3.5.1/animate.min.css" rel="stylesheet">



    <link href="//cdn.bootcss.com/fancybox/2.1.5/jquery.fancybox.min.css" rel="stylesheet">



    <script src="//cdn.bootcss.com/pace/1.0.2/pace.min.js"></script>
    <link href="//cdn.bootcss.com/pace/1.0.2/themes/blue/pace-theme-minimal.css" rel="stylesheet">


<link rel="stylesheet" href="/css/style.css">



<link href="//cdn.bootcss.com/font-awesome/4.6.3/css/font-awesome.min.css" rel="stylesheet">


<title>第六章 组织Cython代码 | HatBoy的个人主页</title>

<script src="//cdn.bootcss.com/jquery/2.2.4/jquery.min.js"></script>
<script src="//cdn.bootcss.com/clipboard.js/1.5.10/clipboard.min.js"></script>

<script>
    var yiliaConfig = {
        fancybox: true,
        animate: true,
        isHome: false,
        isPost: true,
        isArchive: false,
        isTag: false,
        isCategory: false,
        fancybox_js: "//cdn.bootcss.com/fancybox/2.1.5/jquery.fancybox.min.js",
        scrollreveal: "//cdn.bootcss.com/scrollReveal.js/3.1.4/scrollreveal.min.js",
        search: true
    }
</script>


    <script>
        yiliaConfig.jquery_ui = [true, "//cdn.bootcss.com/jqueryui/1.10.4/jquery-ui.min.js", "//cdn.bootcss.com/jqueryui/1.10.4/css/jquery-ui.min.css"];
    </script>



    <script> yiliaConfig.rootUrl = "\/";</script>





    <script>
        var _hmt = _hmt || [];
        (function() {
            var hm = document.createElement("script");
            hm.src = "//hm.baidu.com/hm.js?04d04bb57e5c5eaf49059aa602440263";
            var s = document.getElementsByTagName("script")[0]; 
            s.parentNode.insertBefore(hm, s);
        })();
    </script>


</head>
<body>
  <div id="container">
    <div class="left-col">
    <div class="overlay"></div>
<div class="intrude-less">
    <header id="header" class="inner">
        <a href="/" class="profilepic">
            <img src="/img/avatar.jpg" class="animated zoomIn">
        </a>
        <hgroup>
          <h1 class="header-author"><a href="/">HatBoy</a></h1>
        </hgroup>

        

        
            <form id="search-form">
            <input type="text" id="local-search-input" name="q" placeholder="search..." class="search form-control" autocomplete="off" autocorrect="off" searchonload="true" />
            <i class="fa fa-times" onclick="resetSearch()"></i>
            </form>
            <div id="local-search-result"></div>
            <p class='no-result'>No results found <i class='fa fa-spinner fa-pulse'></i></p>
        


        
            <div id="switch-btn" class="switch-btn">
                <div class="icon">
                    <div class="icon-ctn">
                        <div class="icon-wrap icon-house" data-idx="0">
                            <div class="birdhouse"></div>
                            <div class="birdhouse_holes"></div>
                        </div>
                        <div class="icon-wrap icon-ribbon hide" data-idx="1">
                            <div class="ribbon"></div>
                        </div>
                        
                        <div class="icon-wrap icon-link hide" data-idx="2">
                            <div class="loopback_l"></div>
                            <div class="loopback_r"></div>
                        </div>
                        
                        
                        <div class="icon-wrap icon-me hide" data-idx="3">
                            <div class="user"></div>
                            <div class="shoulder"></div>
                        </div>
                        
                    </div>
                    
                </div>
                <div class="tips-box hide">
                    <div class="tips-arrow"></div>
                    <ul class="tips-inner">
                        <li>菜单</li>
                        <li>标签</li>
                        
                        <li>友情链接</li>
                        
                        
                        <li>关于我</li>
                        
                    </ul>
                </div>
            </div>
        

        <div id="switch-area" class="switch-area">
            <div class="switch-wrap">
                <section class="switch-part switch-part1">
                    <nav class="header-menu">
                        <ul>
                        
                            <li><a href="/">主页</a></li>
                        
                            <li><a href="/archives/">所有文章</a></li>
                        
                            <li><a href="/tags/">标签云</a></li>
                        
                            <li><a href="/about/">关于我</a></li>
                        
                        </ul>
                    </nav>
                    <nav class="header-nav">
                        <ul class="social">
                            
                                <a class="fa Email" href="mailto:hatboy-dj@qq.com" title="Email"></a>
                            
                                <a class="fa GitHub" href="https://github.com/HatBoy/" title="GitHub"></a>
                            
                                <a class="fa GitHub博客" href="https://hatboy.github.io/" title="GitHub博客"></a>
                            
                                <a class="fa CSDN" href="http://blog.csdn.net/dj1174232716" title="CSDN"></a>
                            
                        </ul>
                    </nav>
                </section>
                
                
                <section class="switch-part switch-part2">
                    <div class="widget tagcloud" id="js-tagcloud">
                        <ul class="tag-list"><li class="tag-list-item"><a class="tag-list-link" href="/tags/Cython/">Cython</a></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/Python/">Python</a></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/Python-tips/">Python tips</a></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/Python模块tips/">Python模块tips</a></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/Python语法/">Python语法</a></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/asyncio/">asyncio</a></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/异步并发/">异步并发</a></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/调试/">调试</a></li></ul>
                    </div>
                </section>
                
                
                
                <section class="switch-part switch-part3">
                    <div id="js-friends">
                    
                      <a class="main-nav-link switch-friends-link" href="http://fmxfmx.gitee.io/">FMX</a>
                    
                      <a class="main-nav-link switch-friends-link" href="http://jewelz.me/">Jewelz</a>
                    
                      <a class="main-nav-link switch-friends-link" href="https://www.zhihu.com/people/talentisan/activities">轻狂书生</a>
                    
                      <a class="main-nav-link switch-friends-link" href="http://threetop.top/">ZCC</a>
                    
                      <a class="main-nav-link switch-friends-link" href="http://blog.csdn.net/u012017783">ZCC的CSDN</a>
                    
                      <a class="main-nav-link switch-friends-link" href="http://zcc888.gitee.io/">ZCC的博客</a>
                    
                    </div>
                </section>
                

                
                
                <section class="switch-part switch-part4">
                
                    <div id="js-aboutme">一枚爱Python,爱海贼,爱健身,喜欢好玩有趣事物的程序员……</div>
                </section>
                
            </div>
        </div>
    </header>                
</div>
    </div>
    <div class="mid-col">
      <nav id="mobile-nav">
      <div class="overlay">
          <div class="slider-trigger"></div>
          <h1 class="header-author js-mobile-header hide"><a href="/" title="回到主页">HatBoy</a></h1>
      </div>
    <div class="intrude-less">
        <header id="header" class="inner">
            <a href="/" class="profilepic">
                <img src="/img/avatar.jpg" class="animated zoomIn">
            </a>
            <hgroup>
              <h1 class="header-author"><a href="/" title="回到主页">HatBoy</a></h1>
            </hgroup>
            
            <nav class="header-menu">
                <ul>
                
                    <li><a href="/">主页</a></li>
                
                    <li><a href="/archives/">所有文章</a></li>
                
                    <li><a href="/tags/">标签云</a></li>
                
                    <li><a href="/about/">关于我</a></li>
                
                <div class="clearfix"></div>
                </ul>
            </nav>
            <nav class="header-nav">
                        <ul class="social">
                            
                                <a class="fa Email" target="_blank" href="mailto:hatboy-dj@qq.com" title="Email"></a>
                            
                                <a class="fa GitHub" target="_blank" href="https://github.com/HatBoy/" title="GitHub"></a>
                            
                                <a class="fa GitHub博客" target="_blank" href="https://hatboy.github.io/" title="GitHub博客"></a>
                            
                                <a class="fa CSDN" target="_blank" href="http://blog.csdn.net/dj1174232716" title="CSDN"></a>
                            
                        </ul>
            </nav>
        </header>                
    </div>
    <link class="menu-list" tags="标签" friends="友情链接" about="关于我"/>
</nav>
      <div class="body-wrap"><article id="post-第六章-组织Cython代码" class="article article-type-post" itemscope itemprop="blogPost">
  
    <div class="article-meta">
      <a href="/2017/08/16/第六章-组织Cython代码/" class="article-date">
      <time datetime="2017-08-16T01:32:01.000Z" itemprop="datePublished">2017-08-16</time>
</a>


    </div>
  
  <div class="article-inner">
    
      <input type="hidden" class="isFancy" />
    
    
      <header class="article-header">
        
  
    <h1 class="article-title" itemprop="name">
      第六章 组织Cython代码
    </h1>
  

      </header>
      
      <div class="article-info article-info-post">
        

        
    <div class="article-tag tagcloud">
        <ul class="article-tag-list"><li class="article-tag-list-item"><a class="article-tag-list-link" href="/tags/Cython/">Cython</a></li><li class="article-tag-list-item"><a class="article-tag-list-link" href="/tags/Python/">Python</a></li></ul>
    </div>

        <div class="clearfix"></div>
      </div>
      
    
    <div class="article-entry" itemprop="articleBody">
      
          
        <excerpt in="" index="" |="" 首页摘要="">

<p>组织Cython代码</p>
<a id="more"></a>
<the rest="" of="" contents="" |="" 余下全文="">

<p>Python提供了包和模块来帮我们组织项目，让项目代码更加容易理解和重用，在Python中我们可以使用import语句来访问函数，对象，类等其他包和模块中的内容。Cython也允许我们这样做，他完全的支持import语句，它允许我们在运行时访问定义在外部的纯Python模块中的对象或者定义在其他扩展模块中的Python可访问对象。但是Cython不允许Cython模块彼此其他的cdef或者cpdef函数，ctypedef或者struct，而且不允许C级别的代码访问其他的扩展模块。<br>为了解决这个问题，Cython提供了三种文件类型帮助组织包含部分Cython和C级别代码的项目。前面我们知道了Cython的源代码文件.pyx，它是实现文件（implementation files）；下面我们将看到这些文件如何和一个新的Cython文件类型一起工作，这些文件称为定义文件（definition files），后缀是.pyd;第三种Cython文件类型被称为包含文件（include files），后缀名是.pyi。<br>除了这三种文件类型，Cython有一个cimport语句，提供编译时访问C层面的结构的功能，它们会在定义文件（.pyd）中寻找这些结构。<br>本章我们将详细学习Cython的cimport语句和三种文件类型之间的关系。</p>
<h2 id="Cython的实现文件（-pyx）和定义文件（-pyd）"><a href="#Cython的实现文件（-pyx）和定义文件（-pyd）" class="headerlink" title="Cython的实现文件（.pyx）和定义文件（.pyd）"></a>Cython的实现文件（.pyx）和定义文件（.pyd）</h2><p>前面我们一直在使用Cython的实现文件（.pyx），里面的内容是Cython的源代码，但是如果我们需要共享其他的C级别的结构，我们需要创建一个定义文件（.pyd）。<br>有下面一个实现文件：<br><figure class="highlight python"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div><div class="line">21</div><div class="line">22</div><div class="line">23</div><div class="line">24</div><div class="line">25</div><div class="line">26</div><div class="line">27</div></pre></td><td class="code"><pre><div class="line"><span class="comment">#simulator.pyx</span></div><div class="line">ctypedef double real_t</div><div class="line"></div><div class="line">cdef <span class="class"><span class="keyword">class</span> <span class="title">State</span>:</span></div><div class="line">    cdef:</div><div class="line">        unsigned int n_particles</div><div class="line">        real_t *x</div><div class="line">        real_t *vx</div><div class="line"></div><div class="line">    <span class="function"><span class="keyword">def</span> <span class="title">__cinit__</span><span class="params">(...)</span>:</span></div><div class="line">        <span class="comment"># ...</span></div><div class="line">    <span class="function"><span class="keyword">def</span> <span class="title">__dealloc__</span><span class="params">(...)</span>:</span></div><div class="line">        <span class="comment"># ...</span></div><div class="line">    cpdef real_t momentum(self):</div><div class="line">        <span class="comment"># ...</span></div><div class="line"></div><div class="line"><span class="function"><span class="keyword">def</span> <span class="title">setup</span><span class="params">(input_fname)</span>:</span></div><div class="line">    <span class="comment"># ...</span></div><div class="line"></div><div class="line">cpdef run(State st):</div><div class="line">    <span class="comment"># ...calls step function repeatedly...</span></div><div class="line"></div><div class="line">cpdef int step(State st, real_t timestep):</div><div class="line">    <span class="comment"># ...advance st one time step...</span></div><div class="line"></div><div class="line"><span class="function"><span class="keyword">def</span> <span class="title">output</span><span class="params">(State st)</span>:</span></div><div class="line">    <span class="comment"># ...</span></div></pre></td></tr></table></figure></p>
<p>随着simulator.pyx的代码量的增加，维护将越来越困来，为了易于维护和模块化，我们需要将他拆分为逻辑组件。<br>我们首先创建一个simulator.pxd定义文件，在里面定义我们需要共享的C级别的结构，如下：<br><figure class="highlight python"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div></pre></td><td class="code"><pre><div class="line"><span class="comment">#simulator.pxd</span></div><div class="line">ctypedef double real_t</div><div class="line"></div><div class="line">cdef <span class="class"><span class="keyword">class</span> <span class="title">State</span>:</span></div><div class="line">    cdef:</div><div class="line">        unsigned int n_particles</div><div class="line">        real_t *x</div><div class="line">        real_t *vx</div><div class="line">    </div><div class="line">    cpdef real_t momentum(self)</div><div class="line"></div><div class="line">cpdef run(State st)</div><div class="line"></div><div class="line">cpdef int step(State st, real_t timestep)</div></pre></td></tr></table></figure></p>
<p>因为定义文件是在编译时访问的，所以只能将C级别的声明放在里面。此时我们还需要修改实现文件simulator.pyx，因为他们在Cython的命名空间中有相同的名称，我们不能在实现文件中重复定义文件中的内容，这样做编译时会报错。我们的实现文件现在是这样的：<br><figure class="highlight python"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div></pre></td><td class="code"><pre><div class="line"><span class="comment">#simulator.pyx</span></div><div class="line">cdef <span class="class"><span class="keyword">class</span> <span class="title">State</span>:</span></div><div class="line">    <span class="function"><span class="keyword">def</span> <span class="title">__cinit__</span><span class="params">(...)</span>:</span></div><div class="line">        <span class="comment"># ...</span></div><div class="line">    <span class="function"><span class="keyword">def</span> <span class="title">__dealloc__</span><span class="params">(...)</span>:</span></div><div class="line">        <span class="comment"># ...</span></div><div class="line">    cpdef real_t momentum(self):</div><div class="line">        <span class="comment"># ...</span></div><div class="line"></div><div class="line"><span class="function"><span class="keyword">def</span> <span class="title">setup</span><span class="params">(input_fname)</span>:</span></div><div class="line">    <span class="comment"># ...</span></div><div class="line"></div><div class="line">cpdef run(State st):</div><div class="line">    <span class="comment"># ...calls step function repeatedly...</span></div><div class="line"></div><div class="line">cpdef int step(State st, real_t timestep):</div><div class="line">    <span class="comment"># ...advance st one time step...</span></div><div class="line"></div><div class="line"><span class="function"><span class="keyword">def</span> <span class="title">output</span><span class="params">(State st)</span>:</span></div><div class="line">    <span class="comment"># ...</span></div></pre></td></tr></table></figure></p>
<p>ctypedef、cpdef函数和State的属性移动到了定义文件中，def函数和方法照旧。当编译simulator.pyx时，cython编译器会自动寻找simulator.pxd文件，使用里面的声明。<br>什么内容应该放在定义文件中？本质上讲，任何可以被其他Cython模块公开访问的C级别内容都应该放在定义文件中。<br>定义文件中包含下面内容：</p>
<ul>
<li>C类型的声明：ctypedef、struct、union或者enum</li>
<li>外部的C或者C++库的声明：cdef extern代码块</li>
<li>模块级别的cdef和cpdef函数的声明</li>
<li>cdef calss扩展类型的声明</li>
<li>扩展类型的cdef属性</li>
<li>cdef和cpdef方法的声明</li>
<li>C级别inline函数和方法的实现</li>
</ul>
<p>定义文件中不能包含的内容：</p>
<ul>
<li>Python的实现或者不是inline的C的方法和函数的实现</li>
<li>Python类的声明</li>
<li>除IF和DEF宏之外的Python可执行代码</li>
</ul>
<h2 id="cimport语句"><a href="#cimport语句" class="headerlink" title="cimport语句"></a>cimport语句</h2><p>假设现在有一个代码需要重用前面实现的simulator.pyx，我们可以这样写：<br><figure class="highlight python"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div></pre></td><td class="code"><pre><div class="line"><span class="keyword">from</span> simulator cimport State, step, real_t</div><div class="line"><span class="keyword">from</span> simulator <span class="keyword">import</span> setup <span class="keyword">as</span> sim_setup</div><div class="line"></div><div class="line">cdef <span class="class"><span class="keyword">class</span> <span class="title">NewState</span><span class="params">(State)</span>:</span></div><div class="line">    cdef:</div><div class="line">        <span class="comment"># ...extra attributes...</span></div><div class="line">    <span class="function"><span class="keyword">def</span> <span class="title">__cinit__</span><span class="params">(self, ...)</span>:</span></div><div class="line">        <span class="comment"># ...</span></div><div class="line">    <span class="function"><span class="keyword">def</span> <span class="title">__dealloc__</span><span class="params">(self)</span>:</span></div><div class="line">        <span class="comment"># ...</span></div><div class="line"></div><div class="line"><span class="function"><span class="keyword">def</span> <span class="title">setup</span><span class="params">(fname)</span>:</span></div><div class="line">    <span class="comment"># ...call sim_setup and tweak things slightly...</span></div><div class="line"></div><div class="line">cpdef run(State st):</div><div class="line">    <span class="comment"># ...improved run that uses simulator.step...</span></div></pre></td></tr></table></figure></p>
<p>第一句我们使用cimport语句导入扩展类型State，step cpdef函数和real_t ctypedef。在编译时访问C级别的代码，cimport会在simulator.pxd定义文件中寻找要导入的对象。然后第二行使用import语句访问setup def函数，import语句访问的Python级别的代码，在运行时导入。<br>cimport语句跟import语句的语法一样，可以使用cimport语句导入.pxd定义文件，使用它当做模块命名空间：<br><figure class="highlight python"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div></pre></td><td class="code"><pre><div class="line">cimport simulator</div><div class="line"></div><div class="line"><span class="comment"># ...</span></div><div class="line">cdef simulator.State st = simulator.State(params)</div><div class="line">cdef simulator.real_t dt = <span class="number">0.01</span></div><div class="line">simulator.step(st, dt)</div><div class="line"></div><div class="line"><span class="comment">#或者</span></div><div class="line">cimport simulator <span class="keyword">as</span> sim</div><div class="line"></div><div class="line"><span class="comment"># ...</span></div><div class="line">cdef sim.State st = sim.State(params)</div><div class="line">cdef sim.real_t dt = <span class="number">0.01</span></div><div class="line">sim.step(st, dt)</div><div class="line"></div><div class="line"><span class="comment">#或者</span></div><div class="line"><span class="keyword">from</span> simulator cimport State <span class="keyword">as</span> sim_state, step <span class="keyword">as</span> sim_step</div></pre></td></tr></table></figure></p>
<p>定义文件也可以包含cdef extern代码块，也可以只用cimport导入，如下：<br><figure class="highlight python"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div><div class="line">21</div><div class="line">22</div><div class="line">23</div><div class="line">24</div><div class="line">25</div><div class="line">26</div><div class="line">27</div><div class="line">28</div><div class="line">29</div><div class="line">30</div><div class="line">31</div><div class="line">32</div></pre></td><td class="code"><pre><div class="line"><span class="comment">#_mersenne_twister.pxd</span></div><div class="line">cdef extern <span class="keyword">from</span> <span class="string">"mt19937ar.h"</span>:</div><div class="line">    <span class="comment"># initializes mt[N] with a seed</span></div><div class="line">    void init_genrand(unsigned long s)</div><div class="line"></div><div class="line">    <span class="comment"># generates a random number on [0,0xffffffff]-interval</span></div><div class="line">    unsigned long genrand_int32()</div><div class="line"></div><div class="line">    <span class="comment"># generates a random number on [0,0x7fffffff]-interval</span></div><div class="line">    long genrand_int31()</div><div class="line"></div><div class="line">    <span class="comment"># generates a random number on [0,1]-real-interval</span></div><div class="line">    double genrand_real1()</div><div class="line"></div><div class="line">    <span class="comment"># generates a random number on [0,1)-real-interval</span></div><div class="line">    double genrand_real2()</div><div class="line"></div><div class="line">    <span class="comment"># generates a random number on (0,1)-real-interval</span></div><div class="line">    double genrand_real3()</div><div class="line"></div><div class="line">    <span class="comment"># generates a random number on [0,1) with 53-bit resolution</span></div><div class="line">    double genrand_res53()</div><div class="line"></div><div class="line"><span class="comment">#可以用下面方式导入使用</span></div><div class="line"><span class="keyword">from</span> _mersenne_twister cimport init_genrand, genrand_real3</div><div class="line"></div><div class="line"><span class="comment">#或者下面方式导入使用</span></div><div class="line">cimport _mersenne_twister <span class="keyword">as</span> mt</div><div class="line"></div><div class="line">mt.init_genrand(<span class="number">42</span>)</div><div class="line"><span class="keyword">for</span> i <span class="keyword">in</span> range(len(x)):</div><div class="line">    x[i] = mt.genrand_real1()</div></pre></td></tr></table></figure></p>
<h2 id="预定义的定义文件"><a href="#预定义的定义文件" class="headerlink" title="预定义的定义文件"></a>预定义的定义文件</h2><p>Cython预先定义了一些常用的C、C++和Python头文件，他们位于Cython源文件的Includes目录。其中C语言的标准库包libc，它包含stdlib、stdio、math、string和stdint的头文件的.pxd文件，还有常用的C++的标准模板库（STL）的定义文件包libcpp，比如string、vector、list、map、pair、set。Python方面，Cython源文件中有C头文件的.pxd，提供了从Cython简单的访问Python/C API的函数。最后一个声明包是numpy，它提供了访问Numpy/C的API。<br>具体看一些例子：<br><figure class="highlight python"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div><div class="line">21</div><div class="line">22</div><div class="line">23</div><div class="line">24</div><div class="line">25</div><div class="line">26</div><div class="line">27</div><div class="line">28</div><div class="line">29</div><div class="line">30</div><div class="line">31</div><div class="line">32</div><div class="line">33</div><div class="line">34</div></pre></td><td class="code"><pre><div class="line"><span class="comment">#通过cimport使用C标准库</span></div><div class="line"><span class="keyword">from</span> libc cimport math</div><div class="line">math.sin(<span class="number">3.14</span>)</div><div class="line"></div><div class="line"><span class="comment">#通过cimport导入具体的函数</span></div><div class="line"><span class="keyword">from</span> libc.math cimport sin</div><div class="line">sin(<span class="number">3.14</span>)</div><div class="line"></div><div class="line"><span class="keyword">from</span> libc.stdlib cimport rand, srand, qsort, malloc, free</div><div class="line">cdef int *a = &lt;int*&gt;malloc(<span class="number">10</span> * sizeof(int))</div><div class="line"></div><div class="line"><span class="keyword">from</span> libc.string cimport memcpy <span class="keyword">as</span> c_memcpy</div><div class="line"></div><div class="line"><span class="comment">#通过cimport导入C++的STL模板类</span></div><div class="line"><span class="keyword">from</span> libcpp.vector cimport vector</div><div class="line">cdef vector[int] *vi = new vector[int](<span class="number">10</span>)</div><div class="line"></div><div class="line"><span class="comment">#通过cimport和import导入相同的函数名，会产生编译错误，如下</span></div><div class="line"><span class="keyword">from</span> libc.math cimport sin</div><div class="line"><span class="keyword">from</span> math <span class="keyword">import</span> sin</div><div class="line"></div><div class="line"><span class="comment">#可修改成下面这样</span></div><div class="line"><span class="keyword">from</span> libc.math cimport sin <span class="keyword">as</span> csin</div><div class="line"><span class="keyword">from</span> math <span class="keyword">import</span> sin <span class="keyword">as</span> pysin</div><div class="line"></div><div class="line"><span class="comment">#但是导入相同名称的模块名是允许的，结果会调用C标准库的sin函数，所以通常还是建议将模块名通过as重命名</span></div><div class="line"><span class="comment"># compile-time access to functions from math.h</span></div><div class="line"><span class="keyword">from</span> libc cimport math</div><div class="line"><span class="comment"># runtime access to the math module</span></div><div class="line"><span class="keyword">import</span> math</div><div class="line"></div><div class="line"><span class="function"><span class="keyword">def</span> <span class="title">call_sin</span><span class="params">(x)</span>:</span></div><div class="line">    <span class="comment"># which `sin()` does this call?</span></div><div class="line">    <span class="keyword">return</span> math.sin(x)</div></pre></td></tr></table></figure></p>
<p>定义文件和C/C++的头文件有很多相似之处：</p>
<ul>
<li>他们都为了使用外部代码定义了C级别的结构</li>
<li>他们都允许我们将一个大文件拆分为多个组件</li>
<li>他们都定义了公共的C级别接口<br>C和C++访问头文件通过#include预处理指令，本质是对头文件包含文件的包含。Cython的cimport语句更加智能不容易出错，我们可以将它看做是编译时的import语句，和命名空间一起工作。<br>Cython的前身Pyrex，没有cimport语句，使用的是include实现对外部扩展源文件的引用，Cython目前也支持include语句，在一些项目中也有使用。</li>
</ul>
<h2 id="包含文件和包含语句"><a href="#包含文件和包含语句" class="headerlink" title="包含文件和包含语句"></a>包含文件和包含语句</h2><p>假设我们有一个扩展类型，想在所有的主流平台上使用，但是不同平台上的实现方式不同，可能是平台文件系统不兼容或者是平台的API不兼容等原因导致的，我们的目标是抽象这些差异，以透明的方式提供统一的接口。包含文件和include语句提供了一种方法来完成我们的平台兼容性问题的目标。<br>我们放置了三种不同平台的扩展类型的实现在三个.pxi文件中：linux.pxi、darwin.pxi和windows.pxi。三个文件中的一个将在编译中使用，为了将所有的都放在一起，另外一个interface.pyx文件有下面代码，使用IF编译时语句：<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div></pre></td><td class="code"><pre><div class="line">IF UNAME_SYSNAME == &quot;Linux&quot;:</div><div class="line">    include &quot;linux.pxi&quot;</div><div class="line">ELIF UNAME_SYSNAME == &quot;Darwin&quot;:</div><div class="line">    include &quot;darwin.pxi&quot;</div><div class="line">ELIF UNAME_SYSNAME == &quot;Windows&quot;:</div><div class="line">    include &quot;windows.pxi&quot;</div></pre></td></tr></table></figure></p>
<p>注意：同一个源文件include两次，可能会因为重复定义导致编译错误，所以要小心正确的使用include。<br>一些老的代码使用include，新的代码建议使用cimport语句和定义文件，除非是源码级别的包含。<br>使用定义文件，包含文件和实现文件，我们可以使Cython适配任何C或者Python代码。</p>
<h2 id="在Python包中组织和编译Cython模块"><a href="#在Python包中组织和编译Cython模块" class="headerlink" title="在Python包中组织和编译Cython模块"></a>在Python包中组织和编译Cython模块</h2><p>Cython一个显著的特点是允许我们根据性能和分析结果逐步将Python代码转化为Cython代码，从而保持外部接口不变，但是性能得到显著提升。<br>假设我们有下列包结构的项目：<br><figure class="highlight stylus"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div></pre></td><td class="code"><pre><div class="line">pysimulator</div><div class="line">├── __init__.py</div><div class="line">├── main.py</div><div class="line">├── core</div><div class="line">│ ├── __init__.py</div><div class="line">│ ├── core.py</div><div class="line">│ └── sim_state.py</div><div class="line">├── plugins</div><div class="line">│ ├── __init__.py</div><div class="line">│ ├── plugin0.py</div><div class="line">│ └── plugin1.py</div><div class="line">└── utils</div><div class="line">  ├── __init__.py</div><div class="line">  ├── config.py</div><div class="line">  └── output.py</div></pre></td></tr></table></figure></p>
<p>本实例的重点不是实现细节，而是Cython和Python如何在一个框架中共同工作。<br>假设我们分析发现core.py、sim_state.py和plugin0.py需要转换成Cython扩展模块来提升性能，其他的模块还是纯Python保持灵活性。<br>第一步是将.py模块转换到实现文件.pyx并且将其中公共的Cython声明提取到定义文件.pxd中。因为文件分布在不同的包和子包中，我们必须要使用适当的名称来进行导入。<br><figure class="highlight python"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div><div class="line">21</div><div class="line">22</div><div class="line">23</div><div class="line">24</div><div class="line">25</div><div class="line">26</div><div class="line">27</div><div class="line">28</div><div class="line">29</div><div class="line">30</div><div class="line">31</div><div class="line">32</div><div class="line">33</div><div class="line">34</div><div class="line">35</div></pre></td><td class="code"><pre><div class="line"><span class="comment">#sim_state.pxd</span></div><div class="line">ctypedef double real_t</div><div class="line"></div><div class="line">cdef <span class="class"><span class="keyword">class</span> <span class="title">State</span>:</span></div><div class="line">    cdef:</div><div class="line">        unsigned int n_particles</div><div class="line">        real_t *x</div><div class="line">        real_t *vx</div><div class="line"></div><div class="line">    cpdef real_t momentum(self)</div><div class="line"></div><div class="line"><span class="comment">#core.pxd</span></div><div class="line"><span class="keyword">from</span> simulator.core.sim_state cimport State, real_t</div><div class="line"></div><div class="line">cpdef int run(State, list plugins=<span class="keyword">None</span>)</div><div class="line">cpdef step(State st, real_t dt)</div><div class="line"></div><div class="line"><span class="comment">#plugin0.pxd</span></div><div class="line"><span class="keyword">from</span> simulator.core.sim_state cimport State</div><div class="line"></div><div class="line">cpdef run(State st)</div><div class="line"></div><div class="line"><span class="comment">#main.py</span></div><div class="line"><span class="keyword">from</span> simulator.utils.config <span class="keyword">import</span> setup_params</div><div class="line"><span class="keyword">from</span> simulator.utils.output <span class="keyword">import</span> output_state</div><div class="line"><span class="keyword">from</span> simulator.core.sim_state <span class="keyword">import</span> State</div><div class="line"><span class="keyword">from</span> simulator.core.core <span class="keyword">import</span> run</div><div class="line"><span class="keyword">from</span> simulator.plugins <span class="keyword">import</span> plugin0</div><div class="line"></div><div class="line"><span class="function"><span class="keyword">def</span> <span class="title">main</span><span class="params">(fname)</span>:</span></div><div class="line">    params = setup_params(fname)</div><div class="line">    state = State(params)</div><div class="line">    output_state(state)</div><div class="line">    run(state, plugins=[plugin0.run])</div><div class="line">    output_state(state)</div></pre></td></tr></table></figure></p>
<p>经过我们的转换后，main.py还是保持原来的纯Python代码没有变。<br>为了便于运行转换后的项目，我们可以使用pyximport或者将项目构建成一个包，如下：<br><figure class="highlight python"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div></pre></td><td class="code"><pre><div class="line"><span class="comment">#setup.py</span></div><div class="line"><span class="keyword">from</span> distutils.core <span class="keyword">import</span> setup</div><div class="line"><span class="keyword">from</span> Cython.Build <span class="keyword">import</span> cythonize</div><div class="line"></div><div class="line">setup(name=<span class="string">"simulator"</span>,</div><div class="line">      packages=[<span class="string">"simulator"</span>, <span class="string">"simulator.core"</span>, <span class="string">"simulator.utils"</span>, <span class="string">"simulator.plugins"</span>],</div><div class="line">      ext_modules=cythonize(<span class="string">"**/*.pyx"</span>),</div><div class="line">)</div></pre></td></tr></table></figure></p>
<p>使用cythonize和distutils进行打包非常强大和灵活，当.pyx改变时他会自动检测并根据需要重新编译，它还会检测实现文件和定义文件之间的相互依存关系并重新编译所有相关的实现文件。</p>
</the></excerpt>
      
    </div>
    
  </div>
  
    
    <div class="copyright">
        <p><span>本文标题:</span><a href="/2017/08/16/第六章-组织Cython代码/">第六章 组织Cython代码</a></p>
        <p><span>文章作者:</span><a href="/" title="回到主页">HatBoy</a></p>
        <p><span>发布时间:</span>2017-08-16, 09:32:01</p>
        <p><span>最后更新:</span>2017-12-21, 18:15:28</p>
        <p>
            <span>原始链接:</span><a class="post-url" href="/2017/08/16/第六章-组织Cython代码/" title="第六章 组织Cython代码">http://hatboy.gitee.io/2017/08/16/第六章-组织Cython代码/</a>
            <span class="copy-path" data-clipboard-text="原文: http://hatboy.gitee.io/2017/08/16/第六章-组织Cython代码/　　作者: HatBoy" title="点击复制文章链接"><i class="fa fa-clipboard"></i></span>
            <script> var clipboard = new Clipboard('.copy-path'); </script>
        </p>
        <p>
            <span>许可协议:</span><i class="fa fa-creative-commons"></i> <a rel="license" href="http://creativecommons.org/licenses/by-nc-sa/4.0/" title="CC BY-NC-SA 4.0 International" target = "_blank">"署名-非商用-相同方式共享 4.0"</a> 转载请保留原文链接及作者。
        </p>
    </div>



    <nav id="article-nav">
        
            <div id="article-nav-newer" class="article-nav-title">
                <a href="/2017/12/21/第七章-用Cython包装C库/">
                    第七章 用Cython包装C库
                </a>
            </div>
        
        
            <div id="article-nav-older" class="article-nav-title">
                <a href="/2017/08/10/第五章-Cython和扩展类型/">
                    第五章 Cython和扩展类型
                </a>
            </div>
        
    </nav>

  
</article>

    <div id="toc" class="toc-article">
        <strong class="toc-title">文章目录</strong>
        
            <ol class="toc"><li class="toc-item toc-level-2"><a class="toc-link" href="#Cython的实现文件（-pyx）和定义文件（-pyd）"><span class="toc-number">1.</span> <span class="toc-text">Cython的实现文件（.pyx）和定义文件（.pyd）</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#cimport语句"><span class="toc-number">2.</span> <span class="toc-text">cimport语句</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#预定义的定义文件"><span class="toc-number">3.</span> <span class="toc-text">预定义的定义文件</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#包含文件和包含语句"><span class="toc-number">4.</span> <span class="toc-text">包含文件和包含语句</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#在Python包中组织和编译Cython模块"><span class="toc-number">5.</span> <span class="toc-text">在Python包中组织和编译Cython模块</span></a></li></ol>
        
    </div>
    <style>
        .left-col .switch-btn,
        .left-col .switch-area {
            display: none;
        }
        .toc-level-3 i,
        .toc-level-3 ol {
            display: none !important;
        }
    </style>

    <input type="button" id="tocButton" value="隐藏目录"  title="点击按钮隐藏或者显示文章目录">

    <script>
        yiliaConfig.toc = ["隐藏目录", "显示目录", !!"false"];
    </script>



    
<div class="share">
    
        <div class="bdsharebuttonbox">
            <a href="#" class="fa fa-twitter bds_twi" data-cmd="twi" title="分享到推特"></a>
            <a href="#" class="fa fa-weibo bds_tsina" data-cmd="tsina" title="分享到新浪微博"></a>
            <a href="#" class="fa fa-qq bds_sqq" data-cmd="sqq" title="分享给 QQ 好友"></a>
            <a href="#" class="fa fa-files-o bds_copy" data-cmd="copy" title="复制网址"></a>
            <a href="#" class="fa fa fa-envelope-o bds_mail" data-cmd="mail" title="通过邮件分享"></a>
            <a href="#" class="fa fa-weixin bds_weixin" data-cmd="weixin" title="生成文章二维码"></a>
            <a href="#" class="fa fa-share-alt bds_more" data-cmd="more"></i></a>
        </div>
        <script>
            window._bd_share_config={
                "common":{"bdSnsKey":{},"bdText":"第六章 组织Cython代码　| HatBoy的个人主页　","bdMini":"2","bdMiniList":false,"bdPic":"","bdStyle":"0","bdSize":"24"},"share":{}};with(document)0[(getElementsByTagName('head')[0]||body).appendChild(createElement('script')).src='http://bdimg.share.baidu.com/static/api/js/share.js?v=89860593.js?cdnversion='+~(-new Date()/36e5)];
        </script>
    

    
</div>







    




    <div class="scroll" id="post-nav-button">
        
            <a href="/2017/12/21/第七章-用Cython包装C库/" title="上一篇: 第七章 用Cython包装C库">
                <i class="fa fa-angle-left"></i>
            </a>
        

        <a title="文章列表"><i class="fa fa-bars"></i><i class="fa fa-times"></i></a>

        
            <a href="/2017/08/10/第五章-Cython和扩展类型/" title="下一篇: 第五章 Cython和扩展类型">
                <i class="fa fa-angle-right"></i>
            </a>
        
    </div>

    <ul class="post-list"><li class="post-list-item"><a class="post-list-link" href="/2018/02/27/如何恢复丢失的Python源代码如果它还在内存中运行/">如何恢复丢失的Python源代码如果它还在内存中运行</a></li><li class="post-list-item"><a class="post-list-link" href="/2018/02/08/pathlib：文件系统路径作为对象/">pathlib：文件系统路径作为对象</a></li><li class="post-list-item"><a class="post-list-link" href="/2017/12/21/asyncio：异步IO、事件循环和并发/">asyncio：异步IO、事件循环和并发</a></li><li class="post-list-item"><a class="post-list-link" href="/2017/12/21/asyncio之调试asyncio/">asyncio之调试asyncio</a></li><li class="post-list-item"><a class="post-list-link" href="/2017/12/21/asyncio之协程结合线程和进程/">asyncio之协程结合线程和进程</a></li><li class="post-list-item"><a class="post-list-link" href="/2017/12/21/asyncio之接收Unix信号/">asyncio之接收Unix信号</a></li><li class="post-list-item"><a class="post-list-link" href="/2017/12/21/asyncio之使用子进程/">asyncio之使用子进程</a></li><li class="post-list-item"><a class="post-list-link" href="/2017/12/21/asyncio之与DNS服务进行交互/">asyncio之与DNS服务进行交互</a></li><li class="post-list-item"><a class="post-list-link" href="/2017/12/21/asyncio之使用SSL/">asyncio之使用SSL</a></li><li class="post-list-item"><a class="post-list-link" href="/2017/12/21/asyncio之使用协程和流的异步I-O/">asyncio之使用协程和流的异步I/O</a></li><li class="post-list-item"><a class="post-list-link" href="/2017/12/21/asyncio之协议抽象类的异步I-O/">asyncio之协议抽象类的异步I/O</a></li><li class="post-list-item"><a class="post-list-link" href="/2017/12/21/asyncio之同步原语/">asyncio之同步原语</a></li><li class="post-list-item"><a class="post-list-link" href="/2017/12/21/asyncio之用控制结构组建协程/">asyncio之用控制结构组建协程</a></li><li class="post-list-item"><a class="post-list-link" href="/2017/12/21/asyncio之并发执行Tasks/">asyncio之并发执行Tasks</a></li><li class="post-list-item"><a class="post-list-link" href="/2017/12/21/asyncio之异步生产结果/">asyncio之异步生产结果</a></li><li class="post-list-item"><a class="post-list-link" href="/2017/12/21/asyncio之定时调度常规函数/">asyncio之定时调度常规函数</a></li><li class="post-list-item"><a class="post-list-link" href="/2017/12/21/asyncio之使用协程处理多任务/">asyncio之使用协程处理多任务</a></li><li class="post-list-item"><a class="post-list-link" href="/2017/12/21/asyncio之异步并发的概念/">asyncio之异步并发的概念</a></li><li class="post-list-item"><a class="post-list-link" href="/2017/12/21/Python上下文管理器/">Python上下文管理器</a></li><li class="post-list-item"><a class="post-list-link" href="/2017/12/21/Python-importlib讲解/">Python importlib讲解</a></li><li class="post-list-item"><a class="post-list-link" href="/2017/12/21/第七章-用Cython包装C库/">第七章 用Cython包装C库</a></li><li class="post-list-item"><a class="post-list-link" href="/2017/08/16/第六章-组织Cython代码/">第六章 组织Cython代码</a></li><li class="post-list-item"><a class="post-list-link" href="/2017/08/10/第五章-Cython和扩展类型/">第五章 Cython和扩展类型</a></li><li class="post-list-item"><a class="post-list-link" href="/2017/07/31/第四章-Cython实践：N-body模拟/">第四章 Cython实践：N-body模拟</a></li><li class="post-list-item"><a class="post-list-link" href="/2017/07/31/Python性能分析与调试/">Python性能分析与调试</a></li><li class="post-list-item"><a class="post-list-link" href="/2017/07/17/第三章-深入Cython/">第三章 深入Cython</a></li><li class="post-list-item"><a class="post-list-link" href="/2017/07/03/第二章-编译和运行Cython代码/">第二章 编译和运行Cython代码</a></li><li class="post-list-item"><a class="post-list-link" href="/2017/07/02/第一章-Cython简介/">第一章 Cython简介</a></li></ul>




    <script>
        
    </script>
</div>
      <footer id="footer">
    <div class="outer">
        <div id="footer-info">
            <div class="footer-left">
                <i class="fa fa-copyright"></i> 
                2017-2018 HatBoy
            </div>
            <div class="footer-right">
                <a href="http://hexo.io/" target="_blank" title="快速、简洁且高效的博客框架">Hexo</a>  Theme <a href="https://github.com/MOxFIVE/hexo-theme-yelee" target="_blank" title="简而不减 Hexo 双栏博客主题  v3.5">Yelee</a> by MOxFIVE <i class="fa fa-heart animated infinite pulse"></i>
            </div>
        </div>
        
            <div class="visit">
                
                    <span id="busuanzi_container_site_pv" style='display:none'>
                        <span id="site-visit" title="本站到访数"><i class="fa fa-user" aria-hidden="true"></i><span id="busuanzi_value_site_uv"></span>
                        </span>
                    </span>
                
                
                    <span>| </span>
                
                
                    <span id="busuanzi_container_page_pv" style='display:none'>
                        <span id="page-visit"  title="本页阅读量"><i class="fa fa-eye animated infinite pulse" aria-hidden="true"></i><span id="busuanzi_value_page_pv"></span>
                        </span>
                    </span>
                
            </div>
        
    </div>
</footer>
    </div>
    
<script data-main="/js/main.js" src="//cdn.bootcss.com/require.js/2.2.0/require.min.js"></script>





    <script type="text/x-mathjax-config">
MathJax.Hub.Config({
    tex2jax: {
        inlineMath: [ ['$','$'], ["\\(","\\)"]  ],
        processEscapes: true,
        skipTags: ['script', 'noscript', 'style', 'textarea', 'pre', 'code']
    }
});

MathJax.Hub.Queue(function() {
    var all = MathJax.Hub.getAllJax(), i;
    for(i=0; i < all.length; i += 1) {
        all[i].SourceElement().parentNode.className += ' has-jax';                 
    }       
});
</script>

<script src="//cdn.bootcss.com/mathjax/2.6.1/MathJax.js?config=TeX-AMS-MML_HTMLorMML">
</script>


<div class="scroll" id="scroll">
    <a href="#" title="返回顶部"><i class="fa fa-arrow-up"></i></a>
    <a href="#comments" onclick="load$hide();" title="查看评论"><i class="fa fa-comments-o"></i></a>
    <a href="#footer" title="转到底部"><i class="fa fa-arrow-down"></i></a>
</div>
<script>
    // Open in New Window
    
        $("a").attr("target", "_blank");
        $("#scroll a, #toc a").removeAttr("target");
    
</script>

<script async src="https://dn-lbstatics.qbox.me/busuanzi/2.3/busuanzi.pure.mini.js">
</script>
  </div>
</body>
</html>